package top.easyblog.core.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import top.easyblog.common.exception.DLockException;
import top.easyblog.common.response.ShortlinkResultCode;
import top.easyblog.core.annotation.CostTimeTracker;
import top.easyblog.core.annotation.RequestId;

import java.lang.reflect.Method;

/**
 * @author: frank.huang
 * @date: 2023-12-21 22:19
 */
@Slf4j
@Aspect
@Component
public class CostTimeAspect {


    @Pointcut("@annotation(top.easyblog.core.annotation.CostTimeTracker)")
    public void requestId() {
    }


    @Around("requestId()")
    public Object processApiRequest(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();

        if (!method.isAnnotationPresent(CostTimeTracker.class)) {
            throw new DLockException(ShortlinkResultCode.COST_TIME_TRACKER_ANNOTATION_NOT_FOUND,
                    String.format("方法[%s]签名未找到CostTimeTracker注解", method.getName()));
        }

        log.info("开始执行任务[{}]...", method.getName());
        StopWatch stopWatch = new StopWatch();
        stopWatch.start(this.getClass().getSimpleName());
        Object result = pjp.proceed(pjp.getArgs());
        stopWatch.stop();
        log.info("执行任务[{}]任务结束，耗时 {} ms", method.getName(), stopWatch.getTotalTimeMillis());
        return result;
    }

}
